const Promise = require('bluebird');
const emoji = require('node-emoji');

/**
 * @api {get} /api/admin/v1/users/analyse 用户统计
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户统计
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.analyse = function ({}, {models: {Users}}) {
    return Users.analyseV2();
}

/**
 * @api {get} /api/admin/v1/users/browse 用户列表
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户列表
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.browse = function ({query}, {models: {Users, associations}, controller}) {
    let pagination = controller.pagination({
        params: query,
        filters: ['level', 'role', 'inviter_id', 'partner_id', 'agency_id', 'agency_auto_settle', 'subscribe', 'sex', 'status'],
        likes: ['id', 'tel', 'nickname', 'bank_tel', 'domain', 'domain_pid', 'pid', 'openid']
    });
    if (query.inviter_id === '') {
        pagination.where.inviter_id = null;
    }
    return Users.findAndCountAll(pagination).then(function (data) {
        return associations.relateOne(data, Users, 'inviter_id', 'inviter_user', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function (data) {
        return associations.relateOne(data, Users, 'agency_id', 'agency_user', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function (data) {
        return associations.relateOne(data, Users, 'partner_id', 'partner_user', ['id', 'image', 'username', 'nickname', 'tel']);
    });
}

/**
 * @api {get} /api/admin/v1/users/load 用户详情
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户详情
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.load = function ({query}, {models: {Users}}) {
    return Users.findOne({where: {id: query.id}}).then(function (user) {
        if (!user) {
            return {};
        }
        return Promise.props({
            inviter: user.inviter_id ? Users.findOne({
                where: {id: user.inviter_id},
                attributes: ['id', 'image', 'username', 'nickname', 'tel']
            }).then(function (inviter_user) {
                user.inviter_user = inviter_user;
            }) : null,
            agency: user.agency_id ? Users.findOne({
                where: {id: user.agency_id},
                attributes: ['id', 'image', 'username', 'nickname', 'tel']
            }).then(function (agency_user) {
                user.agency_user = agency_user;
            }) : null,
            partner: user.partner_id ? Users.findOne({
                where: {id: user.partner_id},
                attributes: ['id', 'image', 'username', 'nickname', 'tel']
            }).then(function (partner_user) {
                user.partner_user = partner_user;
            }) : null
        }).then(function () {
            return user;
        });
    });
}

/**
 * @api {post} /api/admin/v1/users/add 用户添加
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户添加
 * @apiPermission 管理员(添加用户权限)
 * @apiVersion 1.0.0
 */
exports.add = function ({body}, {models: {Users}, controller}) {
    body = controller.permissions({body: body, model: Users, permission: 'Admin', include: {password: body.password}});
    return Users.registerV2(body).then(function (result) {
        if (body.inviter_id) {
            return Users.updateInviteCountV2(body.inviter_id).then(function () {
                return result;
            });
        }
        return result;
    });
}

/**
 * @api {post} /api/admin/v1/users/edit 用户编辑
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户编辑
 * @apiPermission 管理员(编辑用户权限)
 * @apiVersion 1.0.0
 */
exports.edit = function ({body}, {models: {Users}, controller, wechat, redis}) {
    let where = {id: body.id};
    body = controller.permissions({body: body, model: Users, permission: 'Admin'});

    if (body.level) {
        if (body.level === 'Agency') {
            body.agency_id = where.id;
        } else if (body.level === 'Partner') {
            body.partner_id = where.id;
            body.agency_id = where.id;
        }
    }
    if (body.pid) {
        let arr = body.pid.split('_');
        if (arr.length != 4 || arr[0] != 'mm') {
            return {success: false, message: 'pid 格式错误'}
        }
        body.alimamaId = arr[1];
        body.mediumId = arr[2];
        body.adPositionId = arr[3];
    }
    if (body.domain_pid) {
        let arr = body.domain_pid.split('_');
        if (arr.length != 4 || arr[0] != 'mm') {
            return {success: false, message: '域名pid 格式错误'}
        }
        body.domain_alimamaId = arr[1];
        body.domain_mediumId = arr[2];
        body.domain_adPositionId = arr[3];
    }
    if (body.qun_pid) {
        let arr = body.qun_pid.split('_');
        if (arr.length != 4 || arr[0] != 'mm') {
            return {success: false, message: '群pid 格式错误'}
        }
        body.qun_alimamaId = arr[1];
        body.qun_mediumId = arr[2];
        body.qun_adPositionId = arr[3];
    }

    return exports.load({query: {id: where.id}}, {models: {Users: Users}}).then(function (oldUser) {
        return Users.update(body, {where: where}).then(function (result) {
            if (!result[0]) {
                return {success: false};
            }
            if (body.status === 'Deactivated') {
                Users.cleanUserSessionV2({id: user.id, redisClient: redis.globalClient});
            }

            if (body.inviter_id && body.inviter_id != oldUser.inviter_id) {
                Users.updateInviteCountV2(body.inviter_id).then(function () {
                    if (oldUser.inviter_id) {
                        Users.updateInviteCountV2(oldUser.inviter_id);
                    }
                });

                if (oldUser.level === 'Agency' || oldUser.level === 'Partner') {
                    Users.updateAgencyCountV2(oldUser.inviter_id).then(function () {
                        if (body.inviter_id) {
                            Users.updateAgencyCountV2(body.inviter_id);
                        }
                    });
                }
            }

            if (body.agency_id && body.agency_id != oldUser.agency_id) {
                Users.updateMemberCountV2(body.agency_id).then(function () {
                    Users.updateInviteCountV2(oldUser.agency_id);
                });
            }

            if (body.level && body.level != oldUser.level) {
                Users.updateAgencyCountV2(body.inviter_id).then(function () {
                    if (oldUser.inviter_id) {
                        Users.updateAgencyCountV2(oldUser.inviter_id);
                    }
                });
            }

            return exports.load({query: {id: where.id}}, {models: {Users: Users}}).then(function (newUser) {
                return {success: true, data: newUser};
            });
        });
    });
}

/**
 * @api {post} /api/admin/v1/users/delete 用户删除
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户删除
 * @apiPermission 管理员(删除用户权限)
 * @apiVersion 1.0.0
 */
exports.delete = function ({body}, {models: {Users}, redis}) {
    return Users.removeV2(body.id).then(function (result) {
        if (result.success) {
            Users.cleanUserSessionV2({id: body.id, redisClient: redis.globalClient});
        }
        return result;
    });
}

/**
 * @api {get} /api/admin/v1/users/validate 用户验证
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户验证
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.validate = function ({body}, {models: {Users}}) {
    let where = {tel: body.tel};
    if (body.id) {
        where.id = {ne: body.id}
    }
    return Users.count({where: where}).then(function (count) {
        return {valid: !(count > 0)};
    });
}

/**
 * @api {get} /api/admin/v1/users/send_msg 发送消息
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-发送消息
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.sendMsg = function ({body, user_id}, {models: {Users, ToUsersTexts}, wechatInstance}) {
    return new Promise(function (resolve) {
        wechatInstance.shopWebApi.sendText(body.openid, body.text, function (err) {
            if (err) {
                console.error('\n', err.stack || err.message);
                return resolve({success: false});
            }
            ToUsersTexts.create({
                openid: body.openid,
                text: body.text,
                admin_id: user_id
            });
            return resolve({success: true});
        });
    });
}

/**
 * @api {post} /api/admin/v1/users/edit_by_wechat 通过微信更新
 */
exports.editByWechat = function ({body}, {models: {Users}, config, wechatInstance, qiniu}) {
    return Users.findOne({where: {id: body.id}}).then(function (user) {
        if (!user || !user.openid) {
            return {success: false};
        }
        return new Promise(function (resolve) {
            wechatInstance.shopWebApi.getUser(user.openid, function (err, result) {
                if (err) {
                    console.error('\n', err.stack || err.message);
                    return resolve({success: false});
                }
                let body = {nickname: emoji.strip(result.nickname || '')};
                qiniu.portraitUpload(config.qiniu, result.headimgurl).then(function (result) {
                    if (result.success) {
                        body.image = result.image;
                    }
                    return Users.update(body, {where: {id: user.id}}).then(function () {
                        return resolve({success: true});
                    });
                });
            });
        });
    });
}

/**
 * @api {get} /api/admin/v1/users/agency_change 邀请转粉丝
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-邀请转粉丝
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.agencyChange = function ({body, user_id}, {models: {Users}}) {
    let {id} = body;
    return Users.findOne({where: {id: id}}).then(function (user) {
        if (user.level === 'Partner' || user.level === 'Agency') {
            return Users.update({agency_id: user.id}, {where: {inviter_id: user.id}}).then(function () {
                return {success: true};
            });
        }
        return {success: false, message: '用户不是代理'};
    });
}

/**
 * @api {get} /api/admin/v1/users/agency_change 取消代理转粉
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-取消代理转粉
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.agencyCancel = function ({body, user_id}, {models: {Users}}) {
    let {id} = body;
    return Users.findOne({where: {id: id}}).then(function (user) {
        if (user.level === 'Partner' || user.level === 'Agency') {
            return {success: false, message: '用户还是代理'};
        }
        let handle = function (agency_id) {
            return Users.update({agency_id: agency_id}, {where: {agency_id: user.id}}).then(function () {
                return {success: true};
            });
        }

        if (!user.inviter_id) {
            return handle(user.partner_id || 1);
        }

        return Users.findOne({where: {id: user.inviter_id}}).then(function (inviter) {
            if (inviter.level === 'Partner' || inviter.level === 'Agency') {
                return handle(inviter.id);
            } else {
                return handle(user.partner_id || 1);
            }
        });
    });
}

/**
 * 获取阿里妈妈媒体列表
 */
exports.alimamaAdzones = function ({query, user_id}, {models: {Users}, spider}) {
    let {id} = query;
    return Users.findOne({where: {id: id}}).then(function (user) {
        if (!user) {
            return {success: false, message: '获取用户失败'};
        }
        return Users.findOne({where: {partner_id: user.partner_id}}).then(function (partner) {
            if (!partner) {
                return {success: false, message: '获取合伙人失败'};
            }
            return spider.alimamaAdzones(partner);
        });
    });
}

/**
 * 创建阿里妈妈广告位
 */
exports.alimamaAdzoneCreate = function ({body, user_id}, {models: {Users}, spider}) {
    let {id, pidName} = body;
    return Users.findOne({where: {id: id}}).then(function (user) {
        if (!user) {
            return {success: false, message: '获取用户失败'};
        }
        if (pidName == 'default') {
            if (user.pid) {
                return {success: false, message: 'pid已经设置'};
            }
        } else if (pidName == 'qun') {
            if (user.qun_pid) {
                return {success: false, message: 'qun_pid已经设置'};
            }
        } else if (pidName == 'domain') {
            if (user.domain_pid) {
                return {success: false, message: 'domain_pid已经设置'};
            }
        } else {
            return {success: false, message: 'pidName参数错误:' + pidName};
        }
        return Users.findOne({where: {partner_id: user.partner_id}}).then(function (partner) {
            if (!partner) {
                return {success: false, message: '获取合伙人失败'};
            }
            if (!partner.tao_user || !partner.alimamaId) {
                return {success: false, message: '合伙人未设置阿里妈妈账号或Pid'};
            }
            if (user.tao_user && partner.tao_user != user.tao_user) {
                return {success: false, message: '合伙人联盟账号跟用户的不一致'};
            }
            return spider.alimamaAdzoneCreate(partner, body).then(function (result) {
                if (result.success) {
                    let data = result.data;
                    let pid = 'mm_' + partner.alimamaId + '_' + data.siteId + '_' + data.adzoneId;
                    let arr = pid.split('_');

                    let updateData = {tao_user: partner.tao_user};
                    if (pidName == 'default') {
                        updateData.pid = pid;
                        updateData.alimamaId = arr[1];
                        updateData.mediumId = arr[2];
                        updateData.adPositionId = arr[3];
                    } else if (pidName == 'qun') {
                        updateData.qun_pid = pid;
                        updateData.qun_alimamaId = arr[1];
                        updateData.qun_mediumId = arr[2];
                        updateData.qun_adPositionId = arr[3];
                    } else if (pidName == 'domain') {
                        updateData.domain_pid = pid;
                        updateData.domain_alimamaId = arr[1];
                        updateData.domain_mediumId = arr[2];
                        updateData.domain_adPositionId = arr[3];
                    }
                    return Users.update(updateData, {where: {id: user.id}}).then(function () {
                        return exports.load({query: {id: user.id}}, {models: {Users: Users}}).then(function (user) {
                            return {success: true, data: user};
                        });
                    });
                }
                return result;
            });
        });
    });
}


/**
 * @api {post} /api/admin/v1/users/image_add 用户添加图片
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户添加图片
 * @apiPermission 管理员(编辑用户权限)
 * @apiVersion 1.0.0
 */
exports.imageAdd = function ({body}, {models: {Images, Users}}) {
    let {type, reference} = body;
    if (!type || !reference) {
        return {success: false, message: '参数错误'};
    }
    return Users.findOne({where: {id: reference}, attributes: ['id', 'image']}).then(function (user) {
        if (!user) {
            return {success: false, message: '用户不存在'};
        }
        return Images.create(body).then(function (image) {
            if (type == 'UserImage' && !user.image) {
                return Users.update({image: body.image}, {where: {id: user.id}}).then(function () {
                    return {success: true, data: image, image: 1};
                });
            }
            return {success: true, data: image};
        });
    });
}

/**
 * @api {post} /api/admin/v1/users/image_edit 用户编辑图片
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户编辑图片
 * @apiPermission 管理员(编辑用户权限)
 * @apiVersion 1.0.0
 */
exports.imageEdit = function ({body}, {models: {Images, Users}}) {
    let {id, operation} = body;
    switch (operation) {
        case 'remove':
            return Images.destroy({where: {id: id}}).then(function (count) {
                return {success: (count > 0)};
            });
            break;
        case 'return_qrcode':
            return Images.findOne({where: {id: id}}).then(function (image) {
                if (!image) {
                    return {success: false, message: '图片不存在'}
                }
                return Users.update({
                    return_qrcode: image.image,
                    return_qrcode_mediaid: null
                }, {where: {id: image.reference}}).then(function () {
                    return {success: true, data: image};
                });
            });
            break;
        case 'join_qrcode':
            return Images.findOne({where: {id: id}}).then(function (image) {
                if (!image) {
                    return {success: false, message: '图片不存在'}
                }
                return Users.update({
                    join_qrcode: image.image,
                    join_qrcode_mediaid: null
                }, {where: {id: image.reference}}).then(function () {
                    return {success: true, data: image};
                });
            });
            break;
        case 'banner':
            return Images.findOne({where: {id: id}}).then(function (image) {
                if (!image) {
                    return {success: false, message: '图片不存在'}
                }
                return Users.update({banner: image.image}, {where: {id: image.reference}}).then(function () {
                    return {success: true, data: image};
                });
            });
            break;
        case 'image':
            return Images.findOne({where: {id: id}}).then(function (image) {
                if (!image) {
                    return {success: false, message: '图片不存在'}
                }
                return Users.update({image: image.image}, {where: {id: image.reference}}).then(function () {
                    return {success: true, data: image};
                });
            });
            break;
    }
}

/**
 * @api {get} /api/admin/v1/users/image_browse 用户浏览图片
 * @apiGroup AdminUsers
 * @apiDescription 用户管理-用户浏览图片
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.imageBrowse = function ({query}, {models: {Images}, controller}) {
    return Images.findAndCountAll(controller.pagination({
        params: query,
        filters: ['type', 'reference'],
        order: [['order_by', 'asc']],
        attributes: ['id', 'type', 'reference', 'image']
    }));
}